//
//  TextField+Extension.swift
//  LetMyselfFreeBigJoy
//
//  Created by 罗晓明 on 2018/8/23.
//  Copyright © 2018年 Rowling. All rights reserved.
//

import Foundation
import UIKit
private var limt = 1000

extension UITextField {
    @IBInspectable public var MaxCharcterCount: Int {
        get {
            return objc_getAssociatedObject(self, &limt) as? Int ?? 1000
        }
        set {
            objc_setAssociatedObject(self, &limt, newValue, .OBJC_ASSOCIATION_ASSIGN)
            NotificationCenter.default.addObserver(self, selector: #selector(textFieldEditChanged(obj:)), name: UITextField.textDidChangeNotification, object: self)
        }
    }
    
    @objc func textFieldEditChanged(obj : Notification) -> () {
        if self != obj.object as? UITextField {
            return
        }
        
        let lang = UIApplication.shared.textInputMode?.primaryLanguage
        if lang == "zh-Hans" {
            let selectedRange = self.markedTextRange
            if selectedRange == nil {
                if (text?.count)! > MaxCharcterCount {
                    text = text?.zm.substring(to: MaxCharcterCount)
                    sendActions(for: .allEditingEvents)
                }
            }
        } else {
            if (text?.count)! > MaxCharcterCount {
                text = text?.zm.substring(to: MaxCharcterCount)
                sendActions(for: .allEditingEvents)
            }
        }
    }
}
